<template>
  <el-dialog :title="title" :visible.sync="isDialog" width="30%" :before-close="close">
    <el-form :model="form" :rules="rules" ref="ruleForm" label-width="100px" class="demo-ruleForm">
      <el-form-item v-for="(item, index) in formList" :label="item.fieldName" :prop="item.field" :key="index">
        <el-input :disabled="item.isDisabled" v-if="item.fieldType == 1" v-model="form[item.field]"></el-input>
        <el-input :disabled="item.isDisabled" v-if="item.fieldType == 2" type="textarea" v-model="form[item.field]"></el-input>
        <el-select v-if="item.fieldType == 3" v-model="form[item.field]" :disabled="item.isDisabled" placeholder="请选择" @change="onChange($event, item)">
          <template v-if="item.fileldValue == 1">
            <el-option v-for="(item, index) in ops1" :key="index" :label="item.value" :value="item.key"></el-option>
          </template>
          <template v-if="item.fileldValue == 2">
            <el-option v-for="(item, index) in ops2" :key="index" :label="item.value" :value="item.key"></el-option>
          </template>
          <template v-if="item.fileldValue == 3">
            <el-option v-for="(item, index) in ops3" :key="index" :label="item.value" :value="item.key"></el-option>
          </template>
          <template v-if="item.fileldValue == 4">
            <el-option v-for="(item, index) in ops4" :key="index" :label="item.value" :value="item.key"></el-option>
          </template>
          <template v-if="item.fileldValue == 5">
            <el-option v-for="(item, index) in ops5" :key="index" :label="item.value" :value="item.key"></el-option>
          </template>
          <template v-if="item.fileldValue == 6">
            <el-option v-for="(item, index) in ops6" :key="index" :label="item.value" :value="item.key"></el-option>
          </template>
          <template v-if="item.fileldValue == 7">
            <el-option v-for="(item, index) in companySection" :key="index" :label="item.name" :value="item.id"></el-option>
          </template>
          <template v-if="item.fileldValue == 8">
            <el-option v-for="(item, index) in item.options" :key="index" :label="item.optiondisplay" :value="item.optionvalue"></el-option>
          </template>
        </el-select>
        <el-date-picker @change="datePickerChange" v-if="item.fieldType == 4" v-model="form[item.field]" :disabled="item.isDisabled" format="yyyy 年 MM 月 dd 日" value-format="yyyy-MM-dd" type="date" placeholder="选择日期"></el-date-picker>
        <template v-if="item.fieldType == 5">
          <el-radio :disabled="item.isDisabled" v-for="(item, index) in ops7" v-model="form[item.field]" :key="index" :label="item.key">{{ item.value }}</el-radio>
        </template>
        <div v-if="item.fieldType == 6" id="panel-img">
          <img v-if="form[item.field]" :src="form[item.field]" alt srcset />
          <el-button v-if="form[item.field]" @click="signature(item.field)">重新签名</el-button>
          <el-button class="signatureBtn" v-else @click="signature(item.field)">请将文字签到此处</el-button>
        </div>
        <div v-if="item.fieldType == 7" class="upload">
          <div v-for="(url, ind) in form[item.field] || []" :key="ind" class="avatar">
            <span v-if="!item.isDisabled" class="del" title="删除" @click="delurl(item.field, ind)">X</span>
            <el-image v-if="url.fileUrl.split('.')[url.fileUrl.split('.').length - 1] == 'png' || url.fileUrl.split('.')[url.fileUrl.split('.').length - 1] == 'jpg' || url.fileUrl.split('.')[url.fileUrl.split('.').length - 1] == 'jpeg' || url.fileUrl.split('.')[url.fileUrl.split('.').length - 1] == 'svg'" :src="url.fileUrl" :preview-src-list="[url.fileUrl]" />
            <img style="width: 100%; height: 100%" v-else src="@/assets/images/folderIcon.png" alt srcset @click="open(url)" />
          </div>
          <el-upload v-if="!item.isDisabled" class="avatar-uploader" action="action" :data="{ field: item.field }" :http-request="uploadSectionFile" :show-file-list="false" list-type="picture-card">
            <i class="el-icon-plus"></i>
          </el-upload>
        </div>
      <el-input :disabled="item.isDisabled" v-if="item.fieldType == 8" v-model="form[item.field]" oninput="value=value.replace(/[^\d.]/g,'')"></el-input>

      <!-- <template v-for="(i, index) in item.fieldItems"  >

        <el-select v-if="i.fieldType == 3" v-model="form[i.field]" :disabled="i.isDisabled" placeholder="请选择">
          
          <template v-if="i.fileldValue == 1">
            <el-option v-for="(item, index) in ops1" :key="index" :label="item.value" :value="item.key"></el-option>
          </template>
          <template v-if="i.fileldValue == 2">
            <el-option v-for="(item, index) in ops2" :key="index" :label="item.value" :value="item.key"></el-option>
          </template>
          <template v-if="i.fileldValue == 3">
            <el-option v-for="(item, index) in ops3" :key="index" :label="item.value" :value="item.key"></el-option>
          </template>
          <template v-if="i.fileldValue == 4">
            <el-option v-for="(item, index) in ops4" :key="index" :label="item.value" :value="item.key"></el-option>
          </template>
          <template v-if="i.fileldValue == 5">
            <el-option v-for="(item, index) in ops5" :key="index" :label="item.value" :value="item.key"></el-option>
          </template>
          <template v-if="i.fileldValue == 6">
            <el-option v-for="(item, index) in ops6" :key="index" :label="item.value" :value="item.key"></el-option>
          </template>
          <template v-if="i.fileldValue == 7">
            <el-option v-for="(item, index) in companySection" :key="index" :label="item.name" :value="item.id"></el-option>
          </template>
          <template v-if="i.fileldValue == 8">
            <el-option v-for="(item, index) in i.options" :key="index" :label="item.optiondisplay" :value="item.optionvalue"></el-option>
          </template>
        </el-select>
    
      </template > -->
      </el-form-item>
    </el-form>
    <span slot="footer" v-if="formList.some((i) => !i.isDisabled)" class="dialog-footer">
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="confirm">保 存</el-button>
    </span>
    <el-dialog append-to-body :close-on-click-modal="false" width="660px" title="签字" :modal-append-to-body="false" :visible.sync="issignature">
      <canvas ref="canvas_ref" width="600" height="200" style="border: 1px solid #ccc"></canvas>
      <span slot="footer" class="dialog-footer">
        <el-button @click="issignature = false" round>取 消</el-button>
        <el-button @click="signaturePad.clear()" round>清 除</el-button>
        <el-button type="primary" @click="signatureConfirm" round>确 定</el-button>
      </span>
    </el-dialog>
  </el-dialog>
</template>

<script>
import SignaturePad from "@/util/signature_pad";
import { mapState } from "vuex";
export default {
  props: {
    isDialog: {
      type: Boolean,
      default: false,
    },
    formList: {
      type: Array,
      default: () => [],
    },
    title: {},
    rules: {
      type: Object,
      default: () => ({}),
    },
    formDefaultValue: {
      type: Object,
      default: () => ({}),
    },
  },
  data() {
    return {
      form: {},
      tabs: [],

      issignature: false, //签字dialog
      signaturePad: "",
      field: "", //签名的field

      ops1: [], //用户
      // ops2: [], //部门
      //离职
      ops3: [], //离职原因  key  value
      //调动
      ops4: [], // 异动类型
      ops5: [], //工作地址
      ops6: [], //职级
      ops7: [], //性别
    };
  },
  computed: {
    ...mapState({
      companySection: (state) => state.common.companySection, //公司
    }),
    ops2() {
      //部门
      let depArr = [];
      const callback = (data) => {
        data.map((i) => {
          i.type === 2 && depArr.push(i);
          i.childrens && callback(i.childrens);
        });
      };
      callback(this.companySection);
      return depArr.map((i) => ({ value: i.name, key: i.id }));
    },
  },
  watch: {
    isDialog: {
      handler(newVal) {
        newVal && this.getSelect();
      },
    },
    formDefaultValue: {
      deep: true,
      immediate: true,
      handler(newVal) {
        this.form = newVal;
        console.log(newVal, "newval");
      },
    },
  },
  methods: {
    datePickerChange(e) {
      if (this.title !== "添加合同") return;
      for (const key in this.form) {
        let start, end, startId, endId;
        if (isNaN(this.form[key]) && !isNaN(Date.parse(this.form[key]))) {
          // console.log(this.form[key], "data是日期格式！", this.formList);
          this.formList.map((i) => {
            if (i.fieldName == "合同起始日") start = this.form[i.field], startId = i.field;
            if (i.fieldName == "合同到期日") end = this.form[i.field], endId = i.field;
          });
          if (start > end) {
            this.$message({ type: 'warning', message: '合同到期日不可小于合同起始日' });
            this.form[startId] = '';
            this.form[endId] = '';
          }
        }
      }
    },
    async onChange(employeeId, i) {
      const { field } = i;
      const { title } = this;
      if (field !== "employeeId" || title === "办理调动") return;
      const { data } = await this.$api.optionsManage.GetEmployeeBasicRegister({ employeeId });
      const { departmentId, hiredate, positivedate } = data.data;
      const obj = { departmentId, hireDate: hiredate, positiveDate: positivedate };
      const form = Object.assign({}, this.form, obj);
      this.form = form;
    },
    open(url) {
      window.open(url);
    },
    async delurl(field, inde, disabled = false) { // 删除上传文件
      await this.$confirm("确定删除吗？", "提示", { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning" });
      this.form[field].splice(inde, 1);
      this.$forceUpdate();
      this.$message({ message: "删除成功", type: "success" });
    },
    async uploadSectionFile(params, disabled = false) { //文件上传
      const { file, data: { field } } = params;
      const form = new FormData();
      form.append("formFile", file);
      const fileTypeName = file.name.split(".") ? file.name.split(".")[file.name.split(".").length - 1] : "text";
      const { data: { data } } = await this.$api.optionsManage.uploadOssFile(form, { fileTypeName });
      Array.isArray(this.form[field]) ? this.form[field].push(data) : this.form[field] = [data];
      this.$forceUpdate();
      this.$message({ message: "上传成功", type: "success" });
    },
    async signatureConfirm() {
      // 上传签名
      if (this.signaturePad.isEmpty()) return this.$message({ message: "请先提供签名。", type: "warning" });
      const { field } = this;
      const file = this.signaturePad.toDataURL().file;
      const form = new FormData();
      form.append("formFile", file);
      const { data: { data: { fileUrl } } } = await this.$api.optionsManage.uploadOssFile(form, { fileTypeName: "img" });
      this.form[field] = fileUrl;
      this.issignature = false;
    },
    async signature(field) {
      this.field = field;
      this.issignature = true;
      await this.$nextTick();
      this.signaturePad = new SignaturePad(this.$refs.canvas_ref);
    },
    confirm() {
      this.$refs.ruleForm.validate((valid) => {
        if (!valid) return;
        this.$emit("confirm", this.form);
        this.close();
      });
    },
    close() {
      this.form = {};
      this.$emit("update:isDialog", false);
    },
    async getSelect() {
      // Basics_sex性别  PM_levaeReasons离职原因  Basics_changesType异动类型
      // PM_workAddress工作地址  PM_positionLevel职级
      if (this.title == "添加合同" || this.title == "合同详情" || this.title == "续签合同") return;
      const obj = { 办理转正: "GetEmployeeProbationPeriodSelect", 办理离职: "GetEmployeeAwaitLeaveSelect", 办理调动: "GetEmployeeRegularSelect" };
      const { data: { data: ops1 } } = await this.$api.optionsManage[obj[this.title] || "GetEmployeeProbationPeriodSelect"](); //发起人列表
      const { data: { data: ops3 } } = await this.$api.optionsManage.GetEnumDataOptiont({ metaTypeCode: "PM_levaeReasons" });
      const { data: { data: ops4 } } = await this.$api.optionsManage.GetEnumDataOptiont({ metaTypeCode: "Basics_changesType" });
      const { data: { data: ops5 } } = await this.$api.optionsManage.GetEnumDataOptiont({ metaTypeCode: "PM_workAddress" });
      const { data: { data: ops6 } } = await this.$api.optionsManage.GetEnumDataOptiont({ metaTypeCode: "PM_positionLevel" });
      const { data: { data: ops7 } } = await this.$api.optionsManage.GetEnumDataOptiont({ metaTypeCode: "Basics_sex" });
      this.ops1 = ops1, this.ops3 = ops3, this.ops4 = ops4, this.ops5 = ops5, this.ops6 = ops6, this.ops7 = ops7;
    },
  },
};
</script>

<style lang="less" scoped>
.upload {
  display: flex;
  flex-wrap: wrap;
}
:deep( .el-upload--picture-card,
.avatar,
.el-image) {
  width: 75px;
  height: 75px;
  line-height: 85px;
}
.avatar {
  margin: 0 10px 10px 0;
  position: relative;
  .del {
    position: absolute;
    z-index: 99;
    top: -40px;
    right: -5px;
  }
}
#panel-img {
  img {
    width: 200px;
    height: 100px;
  }
}
</style>
